using System;
using System.Net.Sockets;
using XcoAppSpaces.Transport.Sockets.Auth.Contract;
using System.Net;

namespace XcoAppSpaces.Transport.Sockets.Auth
{
	class PrepareAuthentication : IPrepareAuthentication
	{
		private int secondsAfterInvalidConnectionIsClosed;

		public void In_TcpClient(TcpClient client)
		{
#if !SILVERLIGHT
			//Console.WriteLine("PrepareAuthentication.In_TcpClient");
			try
			{
				var stream = client.GetStream();
				int originalTimeout = 0;  
#if !PocketPC //setting the timeout is not supported in compact framework
				originalTimeout = stream.ReadTimeout;
				stream.ReadTimeout = secondsAfterInvalidConnectionIsClosed * 1000;
#endif
				Out_Connection(new ConnectionInfo { Client = client, Stream = stream, OriginalStreamReadTimeout = originalTimeout });
			}
			catch //(Exception ex)
			{
				//Console.WriteLine("ERROR: " + ex.Message);
				Out_Error(client);
			}
#else
			//Silverlight sockets seem to have no configurable timeout??
			//TODO handle timeout in another way?
			Out_Connection(new ConnectionInfo { Client = client });
#endif
		}

		public event ValidConnectionHandler Out_Connection;

		public event TcpClientHandler Out_Error;

		public void Inject(SecuritySettings securitySettings)
		{
			secondsAfterInvalidConnectionIsClosed = securitySettings.SecondsAfterInvalidConnectionIsClosed;
		}
	}
}
